package com.bite.forum.controller;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.config.AppConfig;
import com.bite.forum.model.Article;
import com.bite.forum.model.Board;
import com.bite.forum.model.User;
import com.bite.forum.services.IArticleService;
import com.bite.forum.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequestMapping("/article")
@Tag(name = "帖子接口")
@RestController
public class ArticleController {
    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Operation(summary = "发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Schema(description = "板块id") @RequestParam("boardId") @NotNull Long boardId,
                            @Schema(description = "文章标题") @RequestParam("title") @NotNull String title,
                            @Schema(description = "文章内容") @RequestParam("content") @NotNull String content) {
        // 获取当前会话
        HttpSession session = request.getSession(false);
        // 获取当前用户
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 如果用户被封禁，则返回失败
        if (user.getState() == 1) {
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        // 根据板块id获取板块信息
        Board board = boardService.selectById(boardId.longValue());
        // 如果板块不存在或被封禁或被删除，则返回失败
        if (board == null || board.getState() == 1 || board.getDeleteState() == 2) {
            log.info(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_CREATE);
        }

        // 创建文章对象
        Article article = new Article();
        // 设置文章的板块id
        article.setBoardId(boardId);
        // 设置文章的用户id
        article.setUserId(user.getId());
        // 设置文章的标题
        article.setTitle(title);
        // 设置文章的内容
        article.setContent(content);
        // 调用文章服务创建文章
        articleService.create(article);
        // 返回成功
        return AppResult.success();
    }

    @Operation(summary = "根据板块id获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@Schema(description = "板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        // 定义返回的集合
        List<Article> articles;
        // 判断传入的参数是否为空
        if (boardId == null) {
            // 如果传入的参数为空，查询所有
            articles = articleService.selectAll();
            Article article = articles.get(0);
            User user = article.getUser();
        } else {
            // 如果传入的版块Id不为空，查询指定版块下的帖子列表
            articles = articleService.selectAllByBoardId(boardId);
        }

        // 结果是否为空
        if (articles == null) {
            // 如果结合集为空，那么创建上个空集合
            articles = new ArrayList<>();
        }
        // 响应结果
        return AppResult.success(articles);
    }

    @Operation(summary = "根据帖子id获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
           @Schema(description = "帖子id") @RequestParam(value = "id") @NotNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调用Service，获取帖子详情
        Article article = articleService.selectDetailById(id);
        // 判断结果是否为空
        if (article == null) {
            // 返回错误信息
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if (user.getId().equals(article.getUserId())) {
            // 标识为作者
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @Operation(summary = "更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
        @Schema(description = "帖子id") @RequestParam(value = "id") @NotNull Long id,
        @Schema(description = "帖子标题") @RequestParam(value = "title") @NotNull String title,
        @Schema(description = "帖子内容") @RequestParam(value = "content") @NotNull String content) {
        // 获取当前会话
        HttpSession session = request.getSession(false);
        // 从会话中获取用户信息
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 如果用户被禁用
        if(user.getState() == 1){
            // 记录警告日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            // 返回失败结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        // 根据帖子id查询帖子信息
        Article article = articleService.selectById(id);

        // 如果帖子不存在
        if(article == null){
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 返回失败结果
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if(!user.getId().equals(article.getUserId())){
            // 记录警告日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            // 返回失败结果
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        if(article.getState() == 1 || article.getDeleteState() == 1){
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回失败结果
            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }

        articleService.modify(id, title, content);
        log.info("帖子编辑成功！");

        // 返回成功结果
        return AppResult.success();
    }

    @Operation(summary = "点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,@Schema(description = "帖子id") @RequestParam(value = "id") @NotNull Long id) {
        // 获取当前会话
        HttpSession session = request.getSession(false);
        // 从会话中获取用户信息
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 如果用户被禁用
        if (user.getState() == 1) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            // 返回失败结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        // 根据帖子id点赞
        articleService.thumbsUoById(id);
        // 记录信息日志
        log.info("点赞id为" + id + "成功");
        // 返回成功结果
        return AppResult.success();
    }

    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,@Schema(description = "帖子id") @RequestParam(value = "id") @NotNull Long id) {
        // 获取当前会话
        HttpSession session = request.getSession(false);
        // 从会话中获取用户信息
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 如果用户被禁用
        if (user.getState() == 1) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            // 返回失败结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        // 根据帖子id点赞
        articleService.deleteById(id);
        // 记录信息日志
        log.info("删除id为" + id + "成功");
        // 返回成功结果
        return AppResult.success();
    }

    @Operation(summary = "获取用户回复列表")
    @GetMapping("/getAllByUserId")
    public AppResult getAllByUserId(HttpServletRequest request,
           @Schema(description = "用户Id") @RequestParam(value = "userId", required = false)Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
